package com.ke.jdyd.ui;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.ke.jdyd.R;
import com.ke.jdyd.model.DetailConstant;
import com.ke.jdyd.model.GoodsInfo;
import com.ke.jdyd.presenter.HomePresenter;
import com.ke.jdyd.ui.adapter.HomeAdapter;

import java.util.List;

public class HomeFragment extends Fragment implements HomePresenter.HomeView, HomeAdapter.ItemClickListener {
    private static final String TAG = "HomeFragment";
    private HomePresenter mPresenter;
    private RecyclerView mRecyclerView;
    private HomeAdapter mAdapter;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new HomePresenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: 页面渲染");
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mPresenter.loadData();
    }

    @Override
    public void loadSuccess(List<GoodsInfo> result) {
        if (result != null) {
            mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
            mAdapter = new HomeAdapter(getContext(), result);

            mAdapter.setItemClickListener(new HomeAdapter.ItemClickListener() {
                @Override
                public void onItemClick(String id) {
                    if (!TextUtils.isEmpty(id)) {
                        Intent intent = new Intent(getContext(), DetailActivity.class);
                        intent.putExtra(DetailConstant.EXTRA_ID, id);

                        startActivity(intent);
                    }
                }
            });
            mRecyclerView.setAdapter(mAdapter);
        }
    }

    @Override
    public void loadFailed(String msg) {
        Toast.makeText(getContext(), "登录成功~", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(String id) {
        mPresenter.getGoodsDetail(id);
    }
}
